<template>
  <l-layout
    class="l-tab-page"
    v-if="isInit && !lr_loadPage"
    :top="queryHeight + 12"
  >
    <template #left>
      <l-panel
        v-if="[2].includes(pageScheme.layoutType)"
        style="padding-right: 0"
      >
        <template #title>
          {{ $t(pageScheme.left.title) }}
          <div
            class="tree-setting-btn"
            v-if="
              pageScheme.left.dataType == '2' &&
                lr_hasPageAuth('classifysSetting', 'buttons')
            "
          >
            <el-tooltip effect="dark" content="分类管理" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          :data="leftTreeData"
          :expand-on-click-node="false"
          @node-click="handleLeftNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>

    <template #top>
      <l-panel
        :style="{
          'padding-left': [2].includes(pageScheme.layoutType) ? 0 : 1,
          'padding-top': queryType != '1' ? '4px' : 1,
          'padding-bottom': 0,
        }"
        v-if="queryType != '1'"
      >
        <l-query
          :items="queryItems"
          :height.sync="queryHeight"
          :formData="queryData"
          @search="handleSearch"
        >
          <template
            v-for="queryComponent in queryComponents"
            v-slot:[queryComponent.prop]
          >
            <form-item
              v-model="queryData[queryComponent.prop]"
              :upCtrls="upCtrls"
              :formData="queryData"
              :data="queryComponent"
              :key="queryComponent.prop"
            />
          </template>
        </l-query>
      </l-panel>
    </template>
    <l-panel
      :style="{
        'padding-left': [2].includes(pageScheme.layoutType) ? 0 : 1,
        'padding-top': queryType != '1' ? '4px' : 1,
      }"
    >
      <template #toolLeft>
        <l-query2
          v-if="queryType == '1'"
          :formData="queryData"
          :items="queryItems"
          @search="handleSearch"
        >
          <template
            v-for="queryComponent in queryComponents"
            v-slot:[queryComponent.prop]
          >
            <form-item
              v-model="queryData[queryComponent.prop]"
              :upCtrls="upCtrls"
              :formData="queryData"
              :data="queryComponent"
              :key="queryComponent.prop"
            />
          </template>
        </l-query2>

        <div class="l-panel--item" v-else>
          <el-button
            style="margin-right: 8px"
            v-if="
              pageScheme.btns.findIndex((t) => t.id == 'Add') != -1 &&
                lr_hasPageAuth('Add', 'buttons')
            "
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd()"
            >{{ $t("Add") }}
          </el-button>
          <l-excel-btns></l-excel-btns>
        </div>
      </template>
      <template #toolRight>
        <el-button
          style="margin-right: 8px"
          v-if="isDeleteMore"
          type="danger"
          size="mini"
          icon="el-icon-delete"
          @click="handleDeleteMore"
          >{{ $t("批量Delete") }}
        </el-button>
        <l-tool-btns
          :hasAdd="
            pageScheme.btns.findIndex((t) => t.id == 'Add') != -1 &&
              queryType == '1'
          "
          @click="handleAdd()"
        >
          <l-excel-btns v-if="queryType == '1'"></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :isMultiSelect="isDeleteMore"
        ref="mainTable"
        :columns="lr_getPageColumns(tableColumns)"
        :dataSource="tableData"
        :row-key="rowKey"
        :isPage="isTablePage"
        :tablePage.sync="tableCurrentPage"
        :pageTotal="tableTotal"
        @loadPageData="turnTablePage"
      >
        <template
          v-for="col in tableColumnsByToLabel"
          v-slot:[col.prop]="scope"
        >
          <l-value-to-label
            :value="scope.row[col.prop]"
            :type="col.dataType"
            :code="col.dataCode"
            :valueKey="col.valueKey"
            :labelKey="col.labelKey"
            :options="col.options"
            :format="col.format"
            :setting="col.setting"
            :key="col.prop"
          ></l-value-to-label>
        </template>
        <l-table-btns :btns="tableBtns" @click="handleTableBtnClick" />
      </l-table>
    </l-panel>

    <!--表单区域-->
    <custmer-form
      ref="CustmerForm"
      :isDialog="isDialog"
      :dialogHeight="dialogHeight"
      :dialogWidth="dialogWidth"
      :drawerWidth="drawerWidth"
      :handleSave="handleSave"
      :handleOpenedForm="handleOpenedForm"
      :loadTableData="loadTableData"
      :formInfo="formScheme.formInfo"
      :classifyCode="pageScheme.left.dataCode"
      :wfcode="wfcode"
      :name="name"
    ></custmer-form>

    <l-wordprint-btn
      v-if="wordPrintCode"
      v-show="false"
      :code="wordPrintCode"
      :getFormData="getPrintData"
      ref="wordprintBtn"
    />


    <l-print-btn
      v-if="commonPrintCode"
      v-show="false"
      :code="commonPrintCode"
      :getFormData="getPrintData"
      ref="commonprintBtn"
    />

    
  </l-layout>
</template>

<script>
import { mapGetters } from "vuex";
import CustmerForm from "./custmerForm.vue";

const api = window.$api.custmerForm.module;
const apiScheme = window.$api.custmerForm.scheme;

export default {
  components: {
    CustmerForm,
  },
  data() {
    return {
      lr_isPage: true,
      lr_isCustmerFormPage: true,
      name: "",
      moduleId: "",
      // 表格
      tableLoading: false,
      columns: [{ label: "", prop: "", minWidth: "1" }],
      tableData: [],
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      tableBtns: [],

      // 左侧树形
      leftTreeId: "",

      // 表单
      formSchemeId: "",
      formEditRow: null,
      formEdit: false,

      // 配置信息
      isInit: false,
      pageScheme: {},
      formScheme: {},

      // 主表数据
      mainTable: null,
      mainTableIndex: 0,
      // 组件映射
      componentMap: {},
      // query
      queryData: {},
      queryItems: [],
      queryComponents: [],
      queryHeight: 44,

      isWFlow: false,
      wfcode: "",

      isDetails: false,

      ldparam: {},

      //  批量Deleteid
      selectListId: [],

      selProCode: "",
      selProId: "",

      printType: "word",
      isPrint: false,
      printLoading: null,
    };
  },
  computed: {
    ...mapGetters(["modules"]),
    leftTreeData() {
      const {
        dataType,
        dataCode,
        dataIdKey,
        dataPIdKey,
        dataValueKey,
        dataLabelKey,
        options,
      } = this.pageScheme.left;
      // 1 静态数据 2 数据字典 3 远端数据(数据源)
      switch (dataType) {
        case "1":
          return options;
        case "2":
          return this.lr_dataItemTree(this.lr_dataItem[dataCode]);
        case "3":
          return this.lr_DataSourceTree(
            this.lr_dataSourceData[dataCode],
            dataIdKey,
            dataPIdKey,
            dataValueKey,
            dataLabelKey
          );
        default:
          return [];
      }
    },
    tableColumns() {
      const columns = [];
      this.pageScheme.table.columns.forEach((column) => {
        const columnComponent = this.componentMap[column.prop];
        if (columnComponent.field) {
          const enCode = `${columnComponent.field}${
            this.formScheme.formType == 1
              ? ""
              : this.formScheme.db.findIndex(
                  (t) => t.name == columnComponent.table
                )
          }`;
          const col = {
            label: column.label,
            prop: enCode.toLowerCase(),
            align: column.align,
          };
          if (column.isMinWidth) {
            col.minWidth = column.width;
          } else {
            col.width = column.width;
          }

          const dataTypeRes = this.getComponentDataType(columnComponent);
          col.dataType = dataTypeRes.type;
          col.dataCode = dataTypeRes.code;
          col.valueKey = dataTypeRes.valueKey;
          col.labelKey = dataTypeRes.labelKey;
          col.options = dataTypeRes.options;
          col.format = dataTypeRes.format;
          if (["rate", "switch"].includes(columnComponent.type)) {
            col.setting = columnComponent;
          }

          columns.push(col);
        }
      });

      if (
        columns.length > 0 &&
        columns.findIndex((t) => t.minWidth > 0) == -1
      ) {
        columns.forEach((col) => {
          col.minWidth = col.width;
          delete col.width;
        });
      }
      return columns;
    },
    tableColumnsByToLabel() {
      return this.lr_tableColumnsByToLabel(
        this.lr_getPageColumns(this.tableColumns)
      );
    },
    mainTablePk() {
      return this.formScheme.primaryKey;
    },
    rowKey() {
      if (this.mainTablePk) {
        return `${this.mainTablePk.toLowerCase()}${
          this.formScheme.formType == 1 ? "" : this.mainTableIndex
        }`;
      } else {
        return "";
      }
    },
    isTablePage() {
      return this.pageScheme.table.isPage;
    },
    isDeleteMore() {
      return this.pageScheme.table.isDeleteMore;
    },
    queryType() {
      return this.pageScheme.queryType;
    },
    isDialog() {
      return this.formScheme.formInfo.openType != "2";
    },
    dialogHeight() {
      return this.formScheme.formInfo.dialogHeight || 600;
    },
    dialogWidth() {
      return this.formScheme.formInfo.dialogWidth || 800;
    },
    drawerWidth() {
      return this.formScheme.formInfo.drawerWidth || 600;
    },
    upCtrls() {
      const res = {};
      this.queryComponents.forEach((item) => {
        if (item.upCtrl) {
          res[item.upCtrl] = res[item.upCtrl] || [];
          res[item.upCtrl].push(item.prop);
        }
      });
      return res;
    },

    wordPrintCode() {
      const btn = this.pageScheme.btns.find((t) => t.id == "Wordprint") || {};
      return btn.printCode || "";
    },
    commonPrintCode() {
      const btn = this.pageScheme.btns.find((t) => t.id == "Print") || {};
      console.log(btn,'btn');
      return btn.printCode || "";
    },
  },
  watch: {
    $route: {
      handler(route) {
        if (route.name == "mycustmerForm") {
          this.init();
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 页面初始化
    async init() {
      this.isInit = false;
      const module = this.modules.find(
        (t) => t.f_UrlAddress == this.$route.query.src
      );
      await this.lr_loadPageAuth(); // 加载页面权限
      const res = await this.$awaitWraper(api.getScheme(module.f_UrlAddress));
      this.queryHeight = 44;

      if (res && module.f_UrlAddress == this.$route.query.src) {
        this.id = res.entity.f_Id;
        const moduleId = module.f_ModuleId;

        this.moduleId = module.f_ModuleId;
        if (window.$ldparam) {
          this.ldparam[this.moduleId] = window.$ldparam[this.moduleId];
          window.$ldparam[this.moduleId] = undefined;
        }

        this.pageScheme = JSON.parse(res.entity.f_Scheme);
        this.formScheme = JSON.parse(res.formScheme.f_Scheme);

        // 表单模版id
        this.formSchemeId = res.formScheme.f_Id;
        // 主表
        this.mainTableIndex = this.formScheme.db.findIndex(
          (t) => t.type == "main"
        );
        this.mainTable = this.formScheme.db[this.mainTableIndex];
        // 设置映射值
        this.componentMap = this.getComponentMap(this.formScheme);
        // 设置query
        this.setQueryData(this.pageScheme);
        // 设置按钮
        this.setBtns();

        // 设置左侧树形数据
        this.setTree();

        this.isInit = true;

        this.$nextTick(() => {
          // 加载列表数据
          this.loadTableData(false, moduleId);
        });
      }
    },
    getComponentMap(formScheme) {
      const componentMap = {};
      formScheme.formInfo.tabList.forEach((tab) => {
        tab.components.forEach((component) => {
          componentMap[component.prop] = component;
        });
      });
      return componentMap;
    },
    setQueryData(pageScheme) {
      const queryItems = [];
      const queryComponents = [];
      pageScheme.table.querys.forEach((item) => {
        const prop = item.prop;
        const queryComponent = this.$deepClone(this.componentMap[item.prop]);
        queryComponent.disabled = false;
        queryComponent.readonly = false;

        queryComponents.push(queryComponent);

        if (["switch"].includes(queryComponent.type)) {
          this.$set(
            this.queryData,
            queryComponent.prop,
            this.toValueType(
              queryComponent.valueType,
              queryComponent.default
            ) ||
              this.toValueType(
                queryComponent.valueType,
                queryComponent.inactiveValue
              )
          );
        } else {
          this.$set(this.queryData, queryComponent.prop, undefined);
        }

        if (
          pageScheme.queryType == "1" &&
          ["modifytime", "createtime", "datetime"].includes(queryComponent.type)
        ) {
          queryItems.push({
            label: queryComponent.label,
            prop: prop,
            span: 24,
          });
        } else {
          queryItems.push({
            label: queryComponent.label,
            prop: prop,
            span: 24,
          });
        }

        if (
          ["textarea", "password", "guid", "encode"].includes(
            queryComponent.type
          )
        ) {
          queryComponent.type = "input";
        } else if (["datetime", "time"].includes(queryComponent.type)) {
          queryComponent.dateType = `${queryComponent.dateType}range`;
        } else if (["company"].includes(queryComponent.type)) {
          queryComponent.type = `companySelect`;
        } else if (["department"].includes(queryComponent.type)) {
          queryComponent.type = `departmentSelect`;
        } else if (["createuser", "modifyuser"].includes(queryComponent.type)) {
          queryComponent.type = `userSelect`;
        } else if (["createtime", "modifytime"].includes(queryComponent.type)) {
          queryComponent.type = `datetimerange`;
          queryComponent.dateType = `datetimerange`;
        }

        if (
          [
            "userSelect",
            "departmentSelect",
            `companySelect`,
            "select",
          ].includes(queryComponent.type)
        ) {
          queryComponent.multiple = true;

          if (["select"].includes(queryComponent.type)) {
            queryComponent.collapseTags = true;
          }
        }
      });
      this.queryItems = queryItems;
      this.queryComponents = queryComponents;
    },
    toValueType(type, value) {
      if (!this.$validatenull(value) && !this.$validatenull(type)) {
        switch (type) {
          case "boolean":
            return value == "true";
          case "string":
            return value;
          case "number":
            return Number(value);
        }
      }
    },
    setBtns() {
      const wfbtn = this.pageScheme.btns.find((t) => t.isWFlow && t.wFlowCode);
      if (wfbtn) {
        this.isWFlow = true;
        this.wfcode = wfbtn.wFlowCode;
      } else {
        this.isWFlow = false;
        this.wfcode = "";
      }
      const isSelPro = this.pageScheme.btns.find(
        (t) => t.isRowBtn && t.wFlowCode
      );
      if (isSelPro) {
        this.selProCode = isSelPro.wFlowCode;
        this.selProId = isSelPro.tableColumnCode;
      }

      this.tableBtns = this.pageScheme.btns.filter((t) => t.isRowBtn);
    },
    // 左侧树形数据
    setTree() {
      if (this.pageScheme.layoutType == 2) {
        const { dataType, dataCode } = this.pageScheme.left;
        switch (dataType) {
          case "2":
            this.lr_loadDataItem(dataCode);
            break;
          case "3":
            this.lr_loadDataSourceData(dataCode);
            break;
        }
      }
    },

    // 左侧树形
    handleLeftNodeClick(node) {
      this.leftTreeId = node.value;
      this.loadTableData();
    },
    setTreeNodeValue(queryData) {
      if (this.pageScheme.layoutType == 2) {
        queryData[this.pageScheme.left.colField] =
          this.leftTreeId || queryData[this.pageScheme.left.colField];
      }
    },
    handleSettingClick() {
      this.$refs.CustmerForm.openClassify();
    },

    // 表格
    // 获取组件数据类型
    getComponentDataType(compt) {
      const res = {};
      if (
        [
          "radio",
          "checkbox",
          "select",
          "selectMultiple",
          "treeselect",
          "layerselect",
        ].includes(compt.type)
      ) {
        switch (compt.dataType) {
          case "1":
            res.type = "mydata";
            res.options = compt.options;
            break;
          case "2":
            res.type = "dataItem";
            res.code = compt.dataCode;
            break;
          case "3":
            res.type = "dataSource";
            res.code = compt.dataCode;
            res.valueKey = compt.dataValueKey;
            res.labelKey = compt.dataLabelKey;
            break;
        }
      } else if (
        ["datetime", "createtime", "modifytime"].includes(compt.type)
      ) {
        res.type = "datetime";
        res.format = compt.format || "yyyy-MM-dd HH:mm:ss";
      } else if (["upload"].includes(compt.type)) {
        res.type = "file";
      } else if (["uploadimg"].includes(compt.type)) {
        res.type = "img";
      } else if (["companySelect", "company"].includes(compt.type)) {
        res.type = "company";
      } else if (["departmentSelect", "department"].includes(compt.type)) {
        res.type = "department";
      } else if (
        ["userSelect", "createuser", "modifyuser"].includes(compt.type)
      ) {
        res.type = "user";
      } else if (["areaselect"].includes(compt.type)) {
        res.type = "areas";
      } else {
        res.type = compt.type;
      }
      return res;
    },

    // 表格按钮点击事件
    handleTableBtnClick(btn) {
      let handle = this["handle" + btn.type];
      handle && handle(btn.rowIndex, btn.row);
    },

    async loadTableData(isNotFirst, moduleId) {
      if (!this.isInit) {
        return;
      }

      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      const loading = this.$loading({
        target: this.$refs.mainTable
          ? this.$refs.mainTable.$el
          : "document.body",
        lock: true,
        text: "Loading data...",
        spinner: "el-icon-loading",
      });

      const queryParams = this.$deepClone(this.queryData);

      this.setTreeNodeValue(queryParams);

      const queryData = {
        queryJson: JSON.stringify(queryParams || {}),
      };
      const sidxComponent = this.pageScheme.table.sidx
        ? this.componentMap[this.pageScheme.table.sidx]
        : null;
      if (sidxComponent) {
        queryData.sidx = `${sidxComponent.field}${
          this.formScheme.formType == 1
            ? ""
            : this.formScheme.db.findIndex((t) => t.name == sidxComponent.table)
        }`;

        if (this.pageScheme.table.isDESC) {
          queryData.sidx += " DESC";
        }
      } else if (this.mainTablePk) {
        /*if(this.formScheme.db.length > 1){
            queryData.sidx = `${this.mainTablePk}${this.mainTableIndex}`
        }
        else{
            queryData.sidx = `${this.mainTablePk}`
        }*/
        queryData.sidx = `${this.mainTablePk.replace(
          /,/g,
          `${this.mainTableIndex},`
        )}${this.mainTableIndex}`;
      } else if (this.tableColumns.length > 0) {
        queryData.sidx = this.tableColumns[0].prop;
      }

      if (queryData.sidx == "0") {
        queryData.sidx = "";
      }

      if (!moduleId || moduleId == this.moduleId) {
        if (this.ldparam && this.ldparam[this.moduleId] !== undefined) {
          queryData.ldparam = this.ldparam[this.moduleId];
        } else {
          this.ldparam = {};
        }

        if (this.isTablePage) {
          queryData.paginationInputDto = {
            rows: this.tablePageSize,
            page: this.tableCurrentPage,
            sidx: queryData.sidx,
          };

          //queryData.rows = this.tablePageSize
          //queryData.page = this.tableCurrentPage

          const data = await this.$awaitWraper(
            apiScheme.getDataPage(this.moduleId, this.formSchemeId, queryData)
          );
          this.selectListId = [];
          if (data != null) {
            this.tableData = data.rows; //Object.freeze(data.rows)
            this.tableTotal = data.records;
          } else {
            this.tableData = [];
            this.tableTotal = 0;
          }
        } else {
          this.tableData = await this.$awaitWraper(
            apiScheme.getDataList(this.moduleId, this.formSchemeId, queryData)
          );
        }
      }

      loading.close();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    handleSearch() {
      this.loadTableData();
    },
    handleAdd() {
      if (this.isWFlow) {
        this.$refs.CustmerForm.openWf();
      } else {
        this.formEdit = false;
        this.$refs.CustmerForm.openForm("Add");
      }
    },
    async handleDeleteMore() {
      let data = this.$refs.mainTable.getSelected();

      this.selectListId = data.map(
        (item) =>
          item[
            `${this.mainTablePk.toLowerCase()}${
              this.formScheme.formType == 1 ? "" : this.mainTableIndex
            }`
          ]
      );
      // console.log("批量Delete", data);
      if (this.selectListId.length == 0) {
        this.$message("请先选择数据");
      } else {
        this.$confirm(
          this.$t("此操作将永久Delete数据, 是否继续?"),
          this.$t("Tips"),
          {
            confirmButtonText: this.$t("confirm"),
            cancelButtonText: this.$t("cancel"),
            type: "warning",
          }
        )
          .then(async () => {
            for (let i in this.selectListId) {
              for (let j in this.tableData) {
                if (this.selectListId[i] == this.tableData[j].f_id0) {
                  this.tableData.splice(j, 1);
                  this.tableTotal--;
                }
              }
            }
            //  Clear全选
            setTimeout(() => {
              //设置延迟执行
              console.log("延时 Clear");
              this.$refs.mainTable.clearSelection();
            }, 1);

            await apiScheme.deleteCusterForm(this.formSchemeId, {
              key: this.mainTablePk,
              keyValues: this.selectListId.join(","),
            });
            this.$message({
              type: "success",
              message: "Delete  success",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Delete has been canceled",
            });
          });
      }
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.$refs.CustmerForm.openForm("Edit data");
    },
    handleDetails($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.$refs.CustmerForm.openForm("Details data", true);
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("This operation will permanently delete the data. Do you want to continue?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await apiScheme.removeData(this.formSchemeId, {
            key: this.mainTablePk,
            keyValue: this.getpkeyValue(row),
          });
          this.$message({
            type: "success",
            message: "Delete  success",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Delete has been canceled",
          });
        });
    },

    // 打印
    openPrint(row, printType) {
      this.printLoading = this.$loading({
        target: "document.body",
        lock: true,
        text: `打印数据Loading...`,
        spinner: "el-icon-loading",
      });
      this.formEdit = true;
      this.formEditRow = row;
      this.isPrint = true;

      this.printType = printType;
      this.$refs.CustmerForm.openForm("打印数据", true, true);
    },
    handleWordprint($index, row) {
      this.openPrint(row, "word");
    },
    handlePrint($index, row) {
      this.openPrint(row, "common");
    },
    
    // 流程发起
    handleSelectionProcess($index, row) {
      this.$confirm(this.$t("此操作发起流程, 是否继续?"), this.$t("Tips"), {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning",
      })
        .then(async () => {
          const columnComponent = this.componentMap[this.selProId];
          if (columnComponent.field) {
            const enCode = `${columnComponent.field}${
              this.formScheme.formType == 1
                ? ""
                : this.formScheme.db.findIndex(
                    (t) => t.name == columnComponent.table
                  )
            }`;
            let processId = enCode.toLowerCase();
            await this.$refs.CustmerForm.handleCreateFlow(
              this.selProCode,
              row[processId]
            );
          } else {
            this.$message({
              type: "info",
              message: "发布失败",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已cancel发布",
          });
        });
    },
    async handleSave(showLoading, hideLoading) {
      showLoading();
      if (await this.$refs.CustmerForm.validateForm()) {
        const formData = this.$refs.CustmerForm.getForm();
        const diffFormData = this.$refs.CustmerForm.getDiffFormData();
        const postData = {
          schemeId: this.formSchemeId,
          isUpdate: this.formEdit,
          pkey: this.mainTablePk,
          pkeyValue: this.formEdit ? this.getpkeyValue(this.formEditRow) : "",
          data: JSON.stringify(formData),
          diffFormData: diffFormData,
        };
        const res = await this.$awaitWraper(apiScheme.saveData(postData));

        if (res) {
          await this.$awaitWraper(
            this.$refs.CustmerForm.afterSaveEvent(res, this.formEdit)
          );

          this.$message({
            type: "success",
            message: this.$t("save success!"),
          });
          this.$refs.CustmerForm.closeForm();
          this.loadTableData(true);
        }
      }
      hideLoading();
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (!this.isPrint) {
        showLoading("Loading data");
      }

      if (this.formEdit) {
        if (this.formScheme.formType == 1) {
          let formdata = {};
          formdata[this.mainTable.name] = [this.formEditRow];
          const mainDataQuery = {};
          if (this.formScheme.db.length > 1) {
            this.formScheme.db.forEach((db) => {
              mainDataQuery[db.relationField] = this.formEditRow[
                db.relationField
              ];
            });
            const res = await this.$awaitWraper(
              apiScheme.getViewData(this.formSchemeId, {
                mainData: JSON.stringify(mainDataQuery),
              })
            );
            formdata = {
              ...formdata,
              ...res,
            };
          }
          await this.$refs.CustmerForm.init(formdata);
        } else {
          const data = await this.$awaitWraper(
            apiScheme.getData(this.formSchemeId, {
              key: this.mainTablePk,
              keyValue: this.getpkeyValue(this.formEditRow),
            })
          );
          await this.$refs.CustmerForm.init(data);
        }
      } else {
        await this.$refs.CustmerForm.init();
      }

      if (!this.isPrint) {
        hideLoading();
      } else {
        this.isPrint = false;
        if (this.printType == "word" && this.$refs.wordprintBtn) {
          await this.$refs.wordprintBtn.handleClick();
        }
        else if(this.printType == "common" && this.$refs.commonprintBtn){
          await this.$refs.commonprintBtn.handleClick();
        }
        else{
          this.$message({
            type: "warning",
            message: "请设置打印模版编码!",
          });
        }

        this.$refs.CustmerForm.closeForm();
        this.printLoading.close();
        this.printLoading = null;
      }
    },
    getpkeyValue(row) {
      const keyValue = [];
      const pkeys = this.mainTablePk.split(",");
      pkeys.forEach((pkey) => {
        if (row[`${pkey.toLowerCase()}0`]) {
          keyValue.push(row[`${pkey.toLowerCase()}0`]);
        }
      });
      return String(keyValue);
    },

    getPrintData() {
      return this.$refs.CustmerForm.getPrintData();
    },
  },
};
</script>
